﻿using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    ///  生产系统-排班管理-排班计划
    /// </summary>
    public class ShiftplanningController : Controller
    {
        private readonly IShiftplanningService _shiftplanningService;

        public ShiftplanningController(IShiftplanningService shiftplanningService)
        {
            _shiftplanningService = shiftplanningService;
        }

        /// <summary>
        /// 排班计划查询页面
        /// </summary>
        /// <returns></returns>
        public IActionResult ShiftplanningQuery()
        {
            return View();
        }

        /// <summary>
        /// 获取排班计划分页列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="planNumber">计划编号</param>
        /// <param name="planName">计划名称</param>
        /// <param name="startTime">开始日期</param>
        /// <param name="endTime">结束日期</param>
        /// <param name="teamType">班组类型</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetShiftplanningPageList(int page = 1, int limit = 10, 
            string planNumber = null, string planName = null, string startTime = null, 
            string endTime = null, string teamType = null)
        {
            try
            {
                var query = new ShiftplanningQueryDTO
                {
                    Page = page,
                    Limit = limit,
                    PlanNumber = planNumber,
                    PlanName = planName,
                    StartTime = startTime,
                    EndTime = endTime,
                    TeamType = teamType
                };

                var result = await _shiftplanningService.GetShiftplanningPageList(query);
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new ShiftplanningPageResultDTO
                {
                    Code = 1,
                    Msg = $"查询失败：{ex.Message}",
                    Count = 0,
                    Data = new List<ShiftplanningDTO>()
                });
            }
        }

        /// <summary>
        /// 添加排班计划
        /// </summary>
        /// <param name="shiftplanningDto">排班计划数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddShiftplanning([FromBody] ShiftplanningDTO shiftplanningDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { success = false, message = "数据验证失败" });
                }

                // 自动生成计划编号
                if (string.IsNullOrEmpty(shiftplanningDto.PlanNumber))
                {
                    shiftplanningDto.PlanNumber = GeneratePlanNumber();
                }

                var result = await _shiftplanningService.AddShiftplanning(shiftplanningDto);
                if (result)
                {
                    return Json(new { success = true, message = "排班计划添加成功" });
                }
                else
                {
                    return Json(new { success = false, message = "排班计划添加失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"添加失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取排班计划详情
        /// </summary>
        /// <param name="id">排班计划ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetShiftplanningById(int id)
        {
            try
            {
                var result = await _shiftplanningService.GetShiftplanningById(id);
                if (result != null)
                {
                    return Json(new { success = true, data = result });
                }
                else
                {
                    return Json(new { success = false, message = "未找到指定的排班计划" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取详情失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新排班计划
        /// </summary>
        /// <param name="shiftplanningDto">排班计划数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateShiftplanning([FromBody] ShiftplanningDTO shiftplanningDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { success = false, message = "数据验证失败" });
                }

                var result = await _shiftplanningService.UpdateShiftplanning(shiftplanningDto);
                if (result)
                {
                    return Json(new { success = true, message = "排班计划更新成功" });
                }
                else
                {
                    return Json(new { success = false, message = "排班计划更新失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"更新失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 生成计划编号
        /// </summary>
        /// <returns></returns>
        private string GeneratePlanNumber()
        {
            var now = DateTime.Now;
            var year = now.Year;
            var month = now.Month.ToString().PadLeft(2, '0');
            var day = now.Day.ToString().PadLeft(2, '0');
            var hour = now.Hour.ToString().PadLeft(2, '0');
            var minute = now.Minute.ToString().PadLeft(2, '0');
            var second = now.Second.ToString().PadLeft(2, '0');

            // 生成格式：PLAN + 年月日时分秒，例如：PLAN20250625143025
            return $"PLAN{year}{month}{day}{hour}{minute}{second}";
        }
    }
}
